import {
  type VisaItemType,
  type AllowableCountryItemType,
  type AllowableCountryListParamsType,
  type BannerListItemType,
  getVisaList,
  getAllowableCountryList,
  getBannerList,
  uploadImage,
  deleteUploadImage,
  type ImageItemType,
} from "@/common/apis/app";
import { defineStore } from "pinia";
import { ref } from "vue";

export const useAppStore = defineStore("app", () => {
  // 签证类型列表
  const visaTypeList = ref<VisaItemType[]>([]);
  // 允许的国家列表
  const allowableCountryList = ref<AllowableCountryItemType[]>([]);
  // banner列表
  const bannerList = ref<BannerListItemType[]>([]);

  // 获取签证类型列表
  async function fetchVisaTypeList() {
    try {
      const res = await getVisaList();
      visaTypeList.value = res;
    } catch (error) {
      console.log(error);
    }
  }

  // 获取允许的国家列表
  async function fetchAllowableCountryList(
    params: AllowableCountryListParamsType
  ) {
    try {
      const res = await getAllowableCountryList(params);
      allowableCountryList.value = res;
    } catch (err) {
      console.log(err);
    }
  }

  // 获取轮播图
  async function fetchBannerList() {
    try {
      const res = await getBannerList();
      bannerList.value = res;
    } catch (err) {
      console.log(err);
    }
  }

  // 上传图片
  async function fetchUploadImage(
    filePath: string
  ): Promise<ImageItemType | undefined> {
    try {
      const res = await uploadImage(filePath);
      if (!res || !res.url) {
        return undefined;
      }
      return { id: res.uploaded, url: res.url };
    } catch (err) {
      console.log(err);
      return undefined;
    }
  }

  // 删除已上传的图片
  async function fetchDeleteUploadImage(
    infoId: number,
    imageId: number
  ): Promise<boolean> {
    try {
      const res = await deleteUploadImage(infoId, imageId);
      if (res) {
        return true;
      }
      return false;
    } catch (err) {
      console.log(err);
      return false;
    }
  }

  return {
    visaTypeList,
    allowableCountryList,
    bannerList,
    fetchVisaTypeList,
    fetchAllowableCountryList,
    fetchBannerList,
    fetchUploadImage,
    fetchDeleteUploadImage,
  };
});

export function useAppStoreHook() {
  return useAppStore();
}
